/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.notaria.guerrasalas.bc;

import com.notaria.guerrasalas.be.TipoDocumentoVehiculo;
import com.notaria.guerrasalas.be.Vehiculo;
import gob.satt.comun.jpa.Command;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import oracle.toplink.essentials.config.HintValues;
import oracle.toplink.essentials.config.TopLinkQueryHints;

/**
 *
 * @author Administrador
 */
public class BuscarVehiculoPorPlacaODuoCommand implements Command<Vehiculo> {

    private String criterio;
    private TipoDocumentoVehiculo tipoDocumentoVehiculo;

    public BuscarVehiculoPorPlacaODuoCommand(String criterio, TipoDocumentoVehiculo tipoDocumentoVehiculo) {
        this.criterio = criterio;
        this.tipoDocumentoVehiculo = tipoDocumentoVehiculo;
    }

    @Override
    public Vehiculo execute(EntityManager em) throws Exception {
        Vehiculo vehiculo = null;
        try {
            vehiculo = (Vehiculo) em.createQuery("Select object(o) from Vehiculo o Where UPPER(o." +
                    (tipoDocumentoVehiculo.equals(TipoDocumentoVehiculo.Placa) ? "nroPlaca" : "dua") +
                    ") = ?1")
                    .setParameter(1, criterio.toUpperCase())
                    .setHint(TopLinkQueryHints.REFRESH, HintValues.TRUE)
                    .getSingleResult();
        } catch (NonUniqueResultException e) {
            return null;
        } catch (NoResultException e) {
            return null;
        }
        return vehiculo;
    }
}
